package org.alfresco.rfernandes.zkcmis.login;

import java.io.IOException;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

public class LoginViewCtrl extends SelectorComposer<Window> {

	@Wire
	private Textbox nameTxb, passwordTxb,urlTxb;

	@Wire
	private Label mesgLbl;

	/**
	 * 
	 */
	private static final long serialVersionUID = -6621313276664133901L;

	@Listen("onClick=#confirmBtn")
	public void confirm() throws IOException {
		mesgLbl.setValue("unauthenticated");
		UserCredentialManager.setUser(null);
		doLogin();
		navigateApp();
	}
	
	private void navigateApp() throws IOException {
		Executions.sendRedirect("app");
		
	}

	public void doAfterCompose(Window comp) throws Exception {
	    super.doAfterCompose(comp);
	    User user = UserCredentialManager.getUser();
		if (user != null) {
			navigateApp();
		} 
	}

	private void doLogin() {
		User user = AuthenticationService.authenticate(nameTxb.getValue(),
				passwordTxb.getValue(),urlTxb.getValue());
		UserCredentialManager.setUser(user);
	}
}
